import os
import optparse
import shutil
import subprocess
import sys

def version_promote(original_line_str, head_pattern, customize_version):
  strip_line_str = original_line_str.strip()
  if not strip_line_str.startswith(head_pattern):
    return False
  tail_line_str = strip_line_str[len(head_pattern):].strip()
  # "231.8.179.1"
  has_double_quote = tail_line_str[0] == "\"" and tail_line_str[-1] == "\""
  if has_double_quote:
    tail_line_str = tail_line_str[1:-1]
  # 231,8,179,1
  dot_or_comma = '.' if tail_line_str.find('.') >= 0 else ','
  version_dots = tail_line_str.split(dot_or_comma)
  if len(version_dots) < 3:
    return False
  target_line_str = ' ' * original_line_str.find(head_pattern) + head_pattern
  if customize_version and len(customize_version) > 0:
    customize_dots = customize_version.split('.')
    if len(customize_dots) < 3:
      return False
    version_dots[0] = customize_dots[0]
    version_dots[1] = customize_dots[1]
    version_dots[2] = customize_dots[2]
  else:
    version_dots[2] = str(int(version_dots[2]) + 1)
  target_line_str += (" \"%s\"\n" if has_double_quote else " %s\n") % dot_or_comma.join(version_dots)
  return target_line_str


def main(argv):
  parser = optparse.OptionParser()
  parser.add_option("--version-file-path", dest="version_file_path", help="Path to version file.")
  parser.add_option("--customize-major-version", dest="customize_major_version", help="Major version.")
  parser.add_option("--customize-minor-version", dest="customize_minor_version", help="Minor version.")
  options, args = parser.parse_args(argv)

  if not options.version_file_path:
    print("You must specify version-file-path parameter.")
    return 1

  version_file = open(options.version_file_path, "r")
  if not version_file:
    print("Fail to open %s file for reading." % options.version_file_path)
    return 1

  pattern_to_amends = [
    # VERSION = 231.8.179
    {"pattern": "VERSION =", "isMajor": False},
    # FILEVERSION 231,8,179,1
    {"pattern": "FILEVERSION", "isMajor": False},
    # VALUE "FileVersion", "231.8.179.1"
    {"pattern": "VALUE \"FileVersion\",", "isMajor": False},
    # BIGVERSION = 2023.1.5
    {"pattern": "BIGVERSION =", "isMajor": True},
    # PRODUCTVERSION 2023,1,5
    {"pattern": "PRODUCTVERSION", "isMajor": True},
    # VALUE "ProductVersion", "2023.1.5"
    {"pattern": "VALUE \"ProductVersion\",", "isMajor": True},
  ]

  lines_modified = []
  amend_count = 0
  for line in version_file.readlines():
    amend_line = None
    for pattern in pattern_to_amends:
      amend_line = version_promote(line, pattern["pattern"],
                                   options.customize_major_version if pattern["isMajor"] else options.customize_minor_version)
      if amend_line:
        break
    if amend_line:
        amend_count += 1
    lines_modified.append(amend_line if amend_line else line)

  version_file.close()

  if amend_count == 0:
    print("Fail to amend %s file" % options.version_file_path)
    return 1

  version_file = open(options.version_file_path, "w")
  if not version_file:
    print("Fail to open %s file for writing." % options.version_file_path)
    return 1

  for line in lines_modified:
    version_file.write(line)
  version_file.close()

  return 0;

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))